<template>
  <div class="box-border flex w-full h-full gap-[22px]">
    <div class="flex flex-col flex-1 h-full">
      <div class="flex flex-col flex-1 gap-4">
        <div
          class="h-[166px] w-full px-[60px] py-[45px] bg-white/50 rounded-[12px] border_white box-border"
        >
          <div class="text-[24px] font-semibold">{{ taskDetail.task_name }}</div>
          <div class="flex justify-between text-[18px] mt-6">
            <div>开机时间：{{ taskDetail.create_time }}</div>
            <div>累计检测：{{ taskDetail.cnt }}件</div>
            <div>有效告警：- - 件</div>
            <div>平均节拍：{{ averageBeat }}min/件</div>
          </div>
        </div>
        <div class="flex-1 w-full bg-white/50 rounded-[12px] border_white box-border">
          <Video :url="currentVideoUrl"></Video>
        </div>
      </div>
      <div class="h-[188px] w-full flex items-center justify-around">
        <el-button type="primary" plain class="!w-[315px] !h-[55px]" @click="handleBack"
          >返回</el-button
        >
      </div>
    </div>
    <div
      class="w-[510px] h-full  bg-white/50 rounded-[12px] border_white px-[65px] py-[45px] box-border"
    >
      <div class="w-full h-1/2">
        <el-input
          v-model="currentBeat"
          size="large"
          placeholder="搜索节拍"
          :prefix-icon="Search"
          @input="handleSearch"
        />
        <div
          class="w-full h-[calc(100%-56px)] mt-4 overflow-y-auto scrollbar scrollbar-thumb-gray-200"
        >
          <div v-if="beats.length > 0">
            <div v-for="item in beats" :key="item.beat_id" class="">
              <div
                class="text-[18px] hover:text-blue-400 px-4 h-9 cursor-pointer hover:bg-blue-400/10 flex items-center"
                :class="{ '!bg-blue-500/10 !text-blue-500': item.beat_id === searchResultId }"
                @click="handleSearchResult(item.beat_id)"
              >
                {{ item.name }}
              </div>
            </div>
          </div>
          <div v-else class="py-4 text-center text-gray-400">未找到对应的节拍</div>
        </div>
      </div>
      <div class="box-border w-full pt-10 h-1/2">
        <div
          class="text-[18px] font-semibold rounded-md bg-white border1 flex items-center justify-center w-full h-12"
        >
          检测目标
        </div>
        <div
          class="w-full h-[calc(100%-64px)] mt-4 overflow-y-auto scrollbar scrollbar-thumb-gray-200"
        >
          <div v-for="item in target" :key="item.id" class="flex items-center mb-4 gap-7">
            <el-image
              :src="item.pic_url"
              :preview-src-list="[item.pic_url]"
              fit="contain"
              class="w-[108px] h-[66px]"
            >
              <template #error>
                <div
                  class="flex items-center justify-center w-full h-full text-gray-400 bg-gray-100"
                >
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div class="text-lg">{{ item.detect_target_cname }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Search, Picture } from '@element-plus/icons-vue'
import Video from '@/components/video.vue'
// import Box from '../assets/images/box.png'
import { getTaskDetail } from '@/api/task'
import { getModelDetail } from '@/api/model'

const router = useRouter()
const route = useRoute()
const taskDetail = ref({})
const target = ref([])
const currentBeat = ref('')
const beats = ref([])
const originalBeats = ref([])
const currentVideoUrl = ref('')
const averageBeat = ref('- -')

watch(
  () => route.query,
  async (newVal) => {
    console.log('🐯 ~ watch ~ newVal:', newVal)
    const res1 = await getTaskDetail({ task_id: newVal.task_id })
    taskDetail.value = res1.data

    // 计算平均节拍
    if (taskDetail.value.cnt > 0) {
      const createTime = new Date(taskDetail.value.create_time).getTime()
      const updateTime = new Date(taskDetail.value.update_time).getTime()
      const diffMinutes = (updateTime - createTime) / (1000 * 60) // 转换为分钟
      averageBeat.value = (diffMinutes / taskDetail.value.cnt).toFixed(1)
    }

    const mappedBeats = res1.data.beats.map((item, index) => ({
      ...item,
      name: `节拍${index + 1}`,
    }))
    beats.value = mappedBeats
    originalBeats.value = mappedBeats
    // const timeStr = taskDetail.value.task_name.replace('的任务', '')
    // const year = timeStr.substring(0, 4)
    // const month = timeStr.substring(4, 6)
    // const day = timeStr.substring(6, 8)
    // const hour = timeStr.substring(8, 10)
    // const minute = timeStr.substring(10, 12)
    // taskDetail.value.start_time = `${year}-${month}-${day} ${hour}:${minute}`

    const res2 = await getModelDetail({ id: newVal.model_id })
    target.value = res2.data.targets.map((item) => ({
      ...item,
      pic_url: item.pic_url ? `${import.meta.env.VITE_IMG_URL}${item.pic_url}` : '',
    }))

    // 初始化显示第一个节拍的视频
    if (mappedBeats.length > 0) {
      currentVideoUrl.value = `${import.meta.env.VITE_VIDEO_URL}${mappedBeats[0].video_url}/output.m3u8`

      // currentVideoUrl.value =
      //   'http://playertest.longtailvideo.com/adaptive/bipbop/gear4/prog_index.m3u8'
      searchResultId.value = mappedBeats[0].beat_id
      console.log('🐯 ~ currentVideoUrl.value:', currentVideoUrl.value)
    }
  },
  { immediate: true },
)

const handleBack = () => {
  router.push('/')
}

const handleSearch = () => {
  if (!currentBeat.value.trim()) {
    beats.value = [...originalBeats.value]
    return
  }
  beats.value = originalBeats.value.filter((item) =>
    item.name.toLowerCase().includes(currentBeat.value.toLowerCase().trim()),
  )
}

const searchResultId = ref(-1)
const handleSearchResult = (id) => {
  searchResultId.value = id
  const selectedBeat = beats.value.find((beat) => beat.beat_id === id)
  if (selectedBeat) {
    // 这里需要根据实际情况拼接完整的视频URL
    currentVideoUrl.value = `${import.meta.env.VITE_VIDEO_URL}${selectedBeat.video_url}/output.m3u8`
    // currentVideoUrl.value =
    //   'http://playertest.longtailvideo.com/adaptive/bipbop/gear4/prog_index.m3u8'
  }
  console.log('🐯 ~ handleSearchResult ~ currentVideoUrl.value:', currentVideoUrl.value)
}
</script>

<style scoped>
:deep(.el-button > span) {
  font-size: 16px;
}

.border1 {
  border: 1px solid #e4e7ed;
}
</style>
